﻿using MediatR;
using SuYuanRabbit.Domain.Entities.TraceabilityManagement;
using SuYuanRabbit.ErrorCode;
using SuYuanRabbit.Infrastructure.Interfaces;
using SuYuanRabbit.ReadAPI.Applications.Commands.Shops;
using SuYuanRabbit.ReadAPI.Dtos.Response;

namespace SuYuanRabbit.ReadAPI.Applications.CommandsHanders.Shops
{
    /// <summary>
    /// 查询商品命令处理
    /// </summary>
    public class QueryShopsCommandHander : IRequestHandler<QueryShopsCommand, PaggingResult<ShopsDto>>
    {
        /// <summary>
        /// 商品仓储
        /// </summary>
        private readonly IBaseRepository<Shop> shopRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="shopRepository">商品仓储</param>
        public QueryShopsCommandHander(IBaseRepository<Shop> shopRepository)
        {
            this.shopRepository = shopRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<PaggingResult<ShopsDto>> Handle(QueryShopsCommand request, CancellationToken cancellationToken)
        {
            var shops = await shopRepository.FindAsync(x => x.IsDeleted != true);

            List<ShopsDto> dto = new List<ShopsDto>();
            foreach (var item in shops)
            {
                ShopsDto shopsDto = new ShopsDto()
                {
                    ShopLefeTime = item.ShopLefeTime,
                    ShopName = item.ShopName,
                    ShopProductionBatches = item.ShopProductionBatches,
                    ShopProductionCompany = item.ShopProductionCompany,
                    ShopProductionLisenceNum = item.ShopProductionLisenceNum,
                    AddPerson = item.AddPerson,
                    AddTime = item.AddTime,
                    UpdatePerson = item.UpdatePerson,
                };
                dto.Add(shopsDto);
            }
            //总条数
            int count = dto.Count;
            //总页数
            int pageCount = (int)Math.Ceiling(1.0 * count / request.PageSize);
            //跳过几条
            int skip = (request.PageIndex - 1) * request.PageSize;
            //分页信息
            PaggingResult<ShopsDto> result = new PaggingResult<ShopsDto>
            {
                Data = dto.Skip(skip).Take(request.PageSize).ToList(),
                TotalPage = pageCount,
                TotalCount = count
            };
            return result;
        }
    }
}
